package com.ccf.business.etl.flow;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.component.api.constants.ComponentConstants;
import com.component.api.model.dto.RuleColumnDTO;
import com.common.utils.tool.StringUtil;
import com.ccf.business.etl.model.RuleDict;
import com.ccf.business.etl.model.RuleSynonym;
import com.ccf.business.etl.model.vo.DictionaryColumnVO;
import com.common.model.exception.ParamFomatException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 *
 * @author xianggj
 * @Date 2021/11/30 15:14
 **/
public class DictionarySpecificationParamHandler extends ParamHandler {

    @Override
    protected Map<String, String> finishingParam() {
        Map<String, String> params = getParams();
        String columns = params.get(ComponentConstants.IN_COLUMNS);
        if (StringUtil.isJsonBlank(columns)){
            throw new ParamFomatException("缺少配置参数columns");
        }
        try {
            List<RuleColumnDTO> ruleColumnDTOS = new ArrayList<>();
            List<DictionaryColumnVO> dictionaryColumnVOS = JSON.parseArray(columns, DictionaryColumnVO.class);
            for (DictionaryColumnVO dic : dictionaryColumnVOS) {
                RuleColumnDTO ruleColumnDTO = new RuleColumnDTO();
                ruleColumnDTO.setField(dic.getField());
                RuleSynonym ruleSynonym = iRuleSynonymService.getById(dic.getSynonym());
                if (ruleSynonym != null){
                    String subject = ruleSynonym.getSubject();
                    String synonyms = ruleSynonym.getSynonyms();
                    List<String> synonymList = StrUtil.split(synonyms, RuleSynonym.SEPARATOR);
                    ruleColumnDTO.setSynonyms(synonymList);
                    ruleColumnDTO.setMainVal(subject);
                } else {
                    throw new ParamFomatException("字段"+dic.getField()+"缺少主值");
                }
                RuleDict ruleDict = iRuleDictService.getById(dic.getDisambiguation());
                if (ruleDict != null){
                    RuleColumnDTO.Rule rule = new RuleColumnDTO.Rule();
                    rule.setSimilarity(ruleDict.getSimilarity() == null?null : ruleDict.getSimilarity()/100);
                    rule.setStartWith(ruleDict.getBeforeN());
                    rule.setEndWith(ruleDict.getAfterN());
                    ruleColumnDTO.setDisambiguation(rule);
                }
                ruleColumnDTOS.add(ruleColumnDTO);
            }
            params.put(ComponentConstants.COLUMNS, JSON.toJSONString(ruleColumnDTOS));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ParamFomatException(e.getMessage());
        }
        return params;
    }

}
